package com.yuma.alibaba.controller;

import com.alibaba.cloud.ai.dashscope.api.DashScopeImageApi;
import com.alibaba.cloud.ai.dashscope.api.DashScopeSpeechSynthesisApi;
import com.alibaba.cloud.ai.dashscope.audio.DashScopeSpeechSynthesisModel;
import com.alibaba.cloud.ai.dashscope.audio.DashScopeSpeechSynthesisOptions;
import com.alibaba.cloud.ai.dashscope.audio.synthesis.SpeechSynthesisPrompt;
import com.alibaba.cloud.ai.dashscope.audio.synthesis.SpeechSynthesisResponse;
import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatOptions;
import com.alibaba.cloud.ai.dashscope.image.DashScopeImageModel;
import com.alibaba.cloud.ai.dashscope.image.DashScopeImageOptions;
import com.google.protobuf.compiler.PluginProtos;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.memory.InMemoryChatMemory;
import org.springframework.ai.image.ImagePrompt;
import org.springframework.ai.image.ImageResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.net.URI;
import java.net.URL;
import java.nio.ByteBuffer;

@RestController
public class AlibabaController {

    private ChatClient chatClient;

    public AlibabaController(ChatClient.Builder chatClientBuilder) {
        this.chatClient = chatClientBuilder
                .defaultSystem("你是一个博学的智能聊天助手，请根据用户提问回答问题.")
                .defaultAdvisors(
                        new MessageChatMemoryAdvisor(new InMemoryChatMemory())  // 带记忆的聊天建议
                        //new SimpleLoggerAdvisor()  // 设置简单日志建议
                )
                .defaultOptions(
                        DashScopeChatOptions.builder()
                                .withTopP(0.7)   // 模型生成结果中，生成最符合用户输入的答案
                                .build()
                )
                .build();
    }

    @GetMapping("/ali/chat")
    public String simpleChat(String query) {
        return chatClient.prompt(query).call().content();
    }

    @Autowired
    private DashScopeImageModel imageModel;

    @GetMapping("/images")
    public void getImage(@RequestParam(value = "msg", defaultValue = "生成一只小猫") String msg,
                         HttpServletResponse response) {
        ImageResponse imageResponse = imageModel.call(
                new ImagePrompt(msg,  // 要查询的数据
                        DashScopeImageOptions.builder()   // 选项
                                .withModel(DashScopeImageApi.ImageModel.WANX_V1.value)  // 图片模型
                                .withN(4)
                                .withWidth(1024)
                                .withHeight(1024)
                                .build()));
        String imageUrl = imageResponse.getResult().getOutput().getUrl();
        try {
            // 把生成的图片的网址内容写到网页上
            URL url = URI.create(imageUrl).toURL();
            InputStream inputStream = url.openStream();
            response.setHeader("Content-Type", MediaType.IMAGE_PNG_VALUE);
            response.getOutputStream().write(inputStream.readAllBytes());
            response.getOutputStream().flush();
        } catch (Exception e) {
        }
    }


    @Autowired
    private DashScopeSpeechSynthesisModel speechSynthesisModel;

    @GetMapping("/tts")
    public void tts(@RequestParam("msg") String msg) throws IOException {
        SpeechSynthesisResponse response = speechSynthesisModel.call(
                new SpeechSynthesisPrompt(
                    msg,   // 生成语音内容
                DashScopeSpeechSynthesisOptions  // 选项
                        .builder()
                        .withSpeed(1.0) // 语速
                        .withPitch(1.0) // 音调
                        .withVolume(50) // 音量
                        .withModel("sambert-zhichu-v1")  // 声音模式
                        .withVoice("zhichu-v1")   // 设置声音
                        .build()
        ));
        File file = new File("F:\\1218\\workspace\\1218workspace\\spring-ai\\alibaba\\src\\main\\resources\\output2.mp3");
        if (!file.exists()){
            file.createNewFile();
        }
        try (FileOutputStream fos = new FileOutputStream(file)) {
            ByteBuffer byteBuffer = response.getResult().getOutput().getAudio();
            fos.write(byteBuffer.array());
            fos.flush();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}